package com.xyauto.theme.view

import android.annotation.SuppressLint
import android.content.Intent
import android.provider.Settings
import android.view.View
import android.view.ViewGroup
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.constraintlayout.widget.ConstraintSet
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.chad.library.adapter.base.BaseDelegateMultiAdapter
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.delegate.BaseMultiTypeDelegate
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.xyauto.theme.App
import com.xyauto.theme.R
import com.xyauto.theme.bean.ISubResBean
import com.xyauto.theme.service.AppListService
import com.xyauto.theme.utils.AutoUtils
import com.xyauto.theme.utils.setImageUrl
import com.xyauto.theme.utils.setSelected

@SuppressLint("NotifyDataSetChanged")
class AppListViewHolder(root: View) : BaseViewHolder(root) {

    companion object {
        private val SETTINGS_ANIMATION_INDEX = "theme.settings.animation.index" to "theme.settings.animation.type"
        private val SETTINGS_ICON_INDEX = "theme.settings.icon.index" to "theme.settings.icon.path"

        private var selectType = 0
        private var animationIndex = 0
        private var iconIndex = 0

    }


    private val mAdapter: AppListAdapter
    private var mAnimationData: MutableList<ISubResBean>? = null
    private var mIconData: MutableList<ISubResBean>? = null

    init {
        AutoUtils.auto(root)
        mAdapter = AppListAdapter()
        initClickListener()
        getViewOrNull<RecyclerView>(R.id.m_select_rv)?.let {
            it.layoutManager = LinearLayoutManager(App.instance, LinearLayoutManager.HORIZONTAL, false)
            it.adapter = mAdapter
        }
        setSelected(R.id.m_tab_animation, selectType == 0)
        setSelected(R.id.m_tab_icon, selectType != 0)
    }


    fun setAnimationData(data: MutableList<ISubResBean>?) {
        mAnimationData = data
        setGone(R.id.m_tab_animation, mAnimationData.isNullOrEmpty())
        if (selectType == 0) {
            mAnimationData?.let(mAdapter::setNewInstance)
        }
    }

    fun setIconData(data: MutableList<ISubResBean>?) {
        mIconData = data
        setGone(R.id.m_tab_icon, mIconData.isNullOrEmpty())
        if (selectType == 1) {
            mIconData?.let(mAdapter::setNewInstance)
        }
    }

    private fun onClick(): (v: View) -> Unit = { view ->
        when (view.id) {
            R.id.m_bg_layout -> {
                App.instance.startService(Intent(AppListService.ACTION_CLOSE_FLOATING_VIEW).apply { setPackage("com.xyauto.theme") })
            }
            R.id.m_tab_animation,
            R.id.m_tab_icon -> {
                val isAnimation = view.id == R.id.m_tab_animation
                if (isAnimation) {
                    selectType = 0
                    mAnimationData?.let(mAdapter::setNewInstance)
                } else {
                    selectType = 1
                    mIconData?.let(mAdapter::setNewInstance)
                }
                setSelected(R.id.m_tab_animation, selectType == 0)
                setSelected(R.id.m_tab_icon, selectType != 0)
            }
        }
    }

    private fun initClickListener() {
        mAdapter.setOnItemClickListener { baseQuickAdapter, view, i ->
            saveData(selectType, i, mAdapter.getItem(i))
            baseQuickAdapter.notifyDataSetChanged()
        }
        onClick().let {
            getViewOrNull<View>(R.id.m_title_view)?.setOnClickListener(it)
            getViewOrNull<View>(R.id.m_close_button)?.setOnClickListener(it)
            getViewOrNull<View>(R.id.m_bg_layout)?.setOnClickListener(it)
            getViewOrNull<View>(R.id.m_tab_animation)?.setOnClickListener(it)
            getViewOrNull<View>(R.id.m_tab_icon)?.setOnClickListener(it)
        }
    }


    fun loadIndex() {
        animationIndex = Settings.Global.getInt(App.instance.contentResolver, SETTINGS_ANIMATION_INDEX.first, 0)
        iconIndex = Settings.Global.getInt(App.instance.contentResolver, SETTINGS_ICON_INDEX.first, 0)
        mAdapter.notifyDataSetChanged()
    }


    private fun saveData(type: Int, index: Int, item: ISubResBean) {
        (if (type == 0) SETTINGS_ANIMATION_INDEX else SETTINGS_ICON_INDEX).let {
            Settings.Global.putInt(App.instance.contentResolver, it.first, index)
            if (type == 0) {
                animationIndex = index
                Settings.Global.putInt(App.instance.contentResolver, it.second, item.getDataPath() as Int)
            } else {
                iconIndex = index
                Settings.Global.putString(App.instance.contentResolver, it.second, item.getDataPath() as String)
            }
        }
    }


    private class AppListAdapter : BaseDelegateMultiAdapter<ISubResBean, BaseViewHolder>() {

        init {
            setMultiTypeDelegate(object : BaseMultiTypeDelegate<ISubResBean>() {
                override fun getItemType(data: List<ISubResBean>, position: Int): Int {
                    return data[position].getType()
                }
            }.apply {
                addItemType(0, R.layout.iten_service_anim)
                addItemType(1, R.layout.iten_service_app_list)
            })
        }


        override fun onCreateDefViewHolder(parent: ViewGroup, viewType: Int): BaseViewHolder {
            return super.onCreateDefViewHolder(parent, viewType).apply {
                val view = itemView
                if (view is ConstraintLayout) {
                    val ratio = if (viewType == 1) AutoUtils.getPreviewScale() else "69:56"
                    val constraintSet = ConstraintSet()
                    constraintSet.clone(view)
                    constraintSet.setDimensionRatio(R.id.m_item_select_viw, ratio)
                    constraintSet.applyTo(view)
                }
                AutoUtils.auto(view)
            }
        }

        override fun convert(holder: BaseViewHolder, item: ISubResBean) {
            val selected = if (selectType == 0) {
                animationIndex
            } else {
                iconIndex
            } == holder.adapterPosition
            when (val image = item.getPreviewImage()) {
                is Int -> holder.setImageResource(R.id.m_item_icon, image)
                is String -> holder.setImageUrl(R.id.m_item_icon, image)
                else -> holder.setImageDrawable(R.id.m_item_icon, null)
            }
            holder
                .setSelected(R.id.m_item_select_viw, selected)
                .setText(R.id.m_item_text, item.getName())
        }
    }


}